package com.zhumo.sz.ipweb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhumo.sz.common.http.HttpClientHelper;
import com.zhumo.sz.config.AddressConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.util.*;

/**
 * @author zhumo
 * @time 2024-02-25
 * @comment ip地址查询网
 */
@Data
@AllArgsConstructor
public class IPSearchProcessor {

    private static IPSearchProcessor ipSearchProcessor;

    static {
        ipSearchProcessor = new IPSearchProcessor();
    }
    public static IPSearchProcessor getInstance() {
        return ipSearchProcessor;
    }

    /**
     * 需求： 获取深圳市所有的街道数据 四级地址 写入MySQL
     * @param name
     * @param httpClient
     * @return
     */
    public List<IPSearchResult> getAllStreets(String name, HttpClient httpClient){
        HashMap<String, Object> params = new HashMap<>();
        params.put("name",name);
        params.put("children",2);
        JSONObject response
                = HttpClientHelper.sendJsonGetRequest(AddressConfig.IP_SEARCH_URL,
                AddressConfig.ContentTypeJsonHeader,params, ContentType.APPLICATION_JSON, httpClient);
        if (isSuccess(response)){
            ArrayList<IPSearchResult> streets = new ArrayList<>();
            JSONObject data = response.getJSONObject("data");
            JSONObject condition = data.getJSONObject("condition");
//            System.out.println(data);
            String city = "";
            if (params.get("children").toString().equals(condition.getString("children"))){
                city = condition.getString("name");
                JSONObject resultJsonObject = JSON.parseObject(JSON.toJSONString(data.getJSONArray("results").get(0)));
                String province = resultJsonObject.getString("province");
                String provinceCode = resultJsonObject.getString("parentcode");
                String finalCity = city;
                Double cityLng = Double.parseDouble(resultJsonObject.getString("lng"));
                Double cityLat = Double.parseDouble(resultJsonObject.getString("lat"));
                resultJsonObject.getJSONArray("childrens").stream().map(str -> JSONObject.parseObject((JSON.toJSONString(str))))
                        .forEach( districtJsObj -> {
                            String district = districtJsObj.getString("district");
                            Double districtLng = Double.valueOf(districtJsObj.getString("lng"));
                            Double districtLat = Double.valueOf(districtJsObj.getString("lat"));
                            districtJsObj.getJSONArray("childrens").stream().map(str -> JSONObject.parseObject(JSON.toJSONString(str)))
                                    .forEach( townJsObj -> {
                                        IPSearchResult ipSearchResult = new IPSearchResult();
                                        String town = townJsObj.getString("name");
                                        ipSearchResult.setTown(town);
                                        ipSearchResult.setProvince(province);
                                        ipSearchResult.setProvinceCode(provinceCode);
                                        ipSearchResult.setCity(finalCity);
                                        ipSearchResult.setCityLng(cityLng);
                                        ipSearchResult.setCityLat(cityLat);
                                        ipSearchResult.setCityCode(resultJsonObject.getString("code"));
                                        ipSearchResult.setCityZipCode(resultJsonObject.getString("zip"));
                                        ipSearchResult.setDistrict(district);
                                        ipSearchResult.setDistrictLat(districtLat);
                                        ipSearchResult.setDistrictLng(districtLng);
                                        ipSearchResult.setDistrictCode(districtJsObj.getString("code"));
                                        ipSearchResult.setDistrictZipCode(districtJsObj.getString("zip"));
                                        ipSearchResult.setJianPin(townJsObj.getString("jianpin"));
                                        ipSearchResult.setLevel(Integer.parseInt(townJsObj.getString("level")));
                                        ipSearchResult.setLng(Double.valueOf(townJsObj.getString("lng")));
                                        ipSearchResult.setLat(Double.valueOf(townJsObj.getString("lat")));
                                        ipSearchResult.setCode(townJsObj.getString("code"));
                                        ipSearchResult.setParentCode(townJsObj.getString("parentcode"));
                                        ipSearchResult.setZipCode(townJsObj.getString("zip"));
                                        ipSearchResult.setPinYin(townJsObj.getString("pinyin"));
                                        Object[] parentCodes = townJsObj.getJSONArray("parentcodes").toArray();
                                        StringBuilder codesBuilder = new StringBuilder();
                                        for (Object c : parentCodes) {
                                            codesBuilder.append(c.toString()).append(",");
                                        }
                                        codesBuilder.delete(codesBuilder.length()-1,codesBuilder.length());
                                        ipSearchResult.setParentCodeList(codesBuilder.toString());
                                        streets.add(ipSearchResult);
                                    });
                        });
                return streets;
            }
        }else {
            return new ArrayList<>();
        }
        return null;
    }

    /**
     * 获取所有地区信息
     * @param name 名称
     * @param httpClient client
     */
    public void getAlLDistricts(String name,HttpClient httpClient){
    }

    /**
     * 获取所有城市信息
     * @param name 名称
     * @param httpClient client
     */
    public void getAllCitys(String name,HttpClient httpClient){

    }


    /**
     * 初步校验请求是否成功
     */
    public static boolean isSuccess(JSONObject response){
        if (Objects.nonNull(response) && response.size() > 0) {
            String message = response.getString("msg");
            String code = response.getString("code");
            return message.equals("ok") && code.equals("0");
        }else {
            return false;
        }
    }

    /**
     * 校验参数与结果是否对应
     */
    public static boolean isMate(String param,String result){
        if (Objects.isNull(result)){
            return false;
        }else {
            return result.equals(param);
        }
    }

    public static void main(String[] args) {
        IPSearchProcessor ipSearchProcessor1 = new IPSearchProcessor();
        CloseableHttpClient aDefault = HttpClients.createDefault();
        List<IPSearchResult> streets = ipSearchProcessor1.getAllStreets("深圳市", aDefault);
        streets.forEach(System.out::println);
    }




}
